package com.yxhl.zoume.core.main.ui.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;

import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.ZouMeApplication;
import com.yxhl.zoume.core.main.presenter.UpdateAppPresenter;
import com.yxhl.zoume.core.main.ui.view.UpdateAppView;
import com.yxhl.zoume.di.component.updateapp.DaggerUpdateAppComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;

import java.io.File;

import javax.inject.Inject;

public class UpdateAppService extends Service implements UpdateAppView {

    /**
     * PendingIntent请求码
     */
    public static final int PENDING_REQUEST_CODE = 1;
    private static final String TAG = "UpdateAppService";
    /**
     * 跳转到安装页面的Uri的Type
     */
    private static final String URI_TYPE = "application/vnd.android.package-archive";
    /**
     * 通知栏请求码
     */
    private static final int NOTIFY_ID = 123;
    /**
     * 进度条总刻度
     */
    private static final int PROGRESS_MAX = 100;


    @Inject
    UpdateAppPresenter mUpdateAppPresenter;
    private NotificationCompat.Builder mBuilder;
    private NotificationManagerCompat mManagerCompat;

    public UpdateAppService() {
    }


    @Override
    public void onCreate() {
        super.onCreate();
        initializeInject();
        mUpdateAppPresenter.attachView(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            final String downloadUrl = intent.getStringExtra(UIConstants.HomePage.INTENT_KEY_UPDATE_APP);
            LOG.e(TAG, "downloadUrl=" + downloadUrl);
            mBuilder = new NotificationCompat.Builder(this);
            mBuilder.setTicker(getString(R.string.update_app_notification_original_ticker))
                    .setContentTitle(getString(R.string.update_app_notification_original_text))
                    .setProgress(0, 0, true)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setAutoCancel(true);

            mManagerCompat = NotificationManagerCompat.from(this);
            mManagerCompat.notify(NOTIFY_ID, mBuilder.build());

            mUpdateAppPresenter.downloadZouMeApp(downloadUrl);
        }
        return START_STICKY;
    }

    /**
     * 在子线程中运行
     *
     * @param ratio
     * @param targetFile
     */
    @Override
    public void renderDataOnSuccess(float ratio, File targetFile) {
        int currentProgress = (int) (PROGRESS_MAX * ratio);
        mBuilder.setContentTitle("正在下载 " + currentProgress + "%");
        mBuilder.setProgress(PROGRESS_MAX, currentProgress, false);

        LOG.e(TAG, "renderDataOnSuccess radio = " + ratio);
        if (ratio < 1) {
            mManagerCompat.notify(NOTIFY_ID, mBuilder.build());
        } else {
            notifyDownloadCompleted(targetFile);
        }
    }

    /**
     * @param targetFile
     */
    private void notifyDownloadCompleted(File targetFile) {
        Uri uri = Uri.fromFile(targetFile);
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setDataAndType(uri, URI_TYPE);
        final PendingIntent installPendingIntent = PendingIntent.getActivity(
                UpdateAppService.this,
                PENDING_REQUEST_CODE,
                installIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        mBuilder.setContentIntent(installPendingIntent);
        mBuilder.setContentTitle(getString(R.string.update_app_notification_completed_title));
        mBuilder.setContentText(getString(R.string.update_app_notification_completed_text));
        mBuilder.setProgress(0, 0, false);
        mManagerCompat.notify(NOTIFY_ID, mBuilder.build());
        //跳转到APK安装页面
        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(installIntent);
    }

    @Override
    public void renderDataOnCompleted() {
        stopSelf();
    }

    @Override
    public void renderDataOnError() {
        updateAppOnError();
        PromptUtils.showShort(this, getString(R.string.update_app_failure));
        stopSelf();
    }

    private void updateAppOnError() {
        mBuilder.setProgress(0, 0, false);
        mBuilder.setContentText(getString(R.string.update_app_notification_error_text));
        mManagerCompat.notify(NOTIFY_ID, mBuilder.build());
    }

    private void initializeInject() {
        DaggerUpdateAppComponent
                .builder()
                .appComponent(ZouMeApplication.application.getAppComponent())
                .activityModule(new ActivityModule(this))
                .build()
                .inject(this);
    }

}
